#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
int main (int argc,char** argv)
{
    if (argc != 2)
    {
        printf("worng argc\n");
        return -1;
    }
    //1.创建服务器socket
    int listenfd =socket(AF_INET,SOCK_STREAM,0);
    if (listenfd  == -1 )
    {
        perror("create socket error!\n");
        return -1;
    }
    //2.绑定服务器的地址和端口到socket上（服务器端IP的可以随意）
    struct sockaddr_in servaddr;
    memset(&servaddr,0,sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    //servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(atoi(argv[1]));
    if ( bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) == -1)
    {
        perror("bind faild!\n");
        close(listenfd);
        return -1;
    }
    //3.将socket设置成监听模式
    if (listen(listenfd,5) != 0) 
    {
        perror("set socket to listen failed!\n");
        close(listenfd);
        return -1;
    }
    //4.接受客户端的连接
    int clifd;
    int socklen = sizeof(struct sockaddr_in);
    struct sockaddr_in cliaddr;
    clifd = accept(listenfd,(struct sockaddr*)&cliaddr,(socklen_t *)&socklen);
    printf("client:%s port:%d is connected!\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
    char buffer[1024];
    while(1)
    {
        int iret;
        memset(buffer,0,sizeof(char)*1024);
        if ((iret = recv(clifd,buffer,sizeof(buffer),0)) <= 0)
        {
            printf("iret=%d\n",iret);
            break;
        }
        printf("receive %s\n",buffer);
        strcpy(buffer,"OK");
        if ((iret=send(clifd,buffer,strlen(buffer),0)) <= 0)
        {
            perror("send faild\n");
            break;
        }
        printf("send %s \n",buffer);
    }
    close(listenfd);
    close(clifd);
    

    return 0;
}
